package com.cyh.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class DateTypeHandler extends BaseTypeHandler<Date> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        //将java类型转成数据库类型
        long time = parameter.getTime();
        ps.setLong(i, time);
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        //将数据库类型转成java类型
        //ResultSet 查询出的结果集
        //columnName 要转换的数据库字段名称
        //获取结果集中需要的数据（long)转换成Date类型并返回
        long along = rs.getLong(columnName);
        Date date = new Date(along);
        return date;
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        //将数据库类型转成java类型
        //columnIndex字段值的位置
        long along = rs.getLong(columnIndex);
        Date date = new Date(along);
        return date;
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        //将数据库类型转成java类型
        long along = cs.getLong(columnIndex);
        Date date = new Date(along);
        return date;
    }
}
